package com.banciyuan.bcywebview.biz.main.group;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.baidu.mobstat.StatService;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.fragment.BaseContainerFragment;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.biz.login.LoginActivity;
import com.banciyuan.bcywebview.biz.main.group.hot.GroupHotFragment;
import com.banciyuan.bcywebview.biz.main.group.talk.GroupTalkFragment;
import com.banciyuan.bcywebview.biz.post.ScreenShots;
import com.banciyuan.bcywebview.biz.post.StartPostActivity;
import com.banciyuan.bcywebview.biz.search.SearchActivity;
import com.banciyuan.bcywebview.utils.constants.EventConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Team;

public class GroupFragment extends BaseContainerFragment implements OnClickListener {

    public static final int TAG = 2;

    private ViewPager mPager;
    private List<Fragment> mList = new ArrayList<>();

    private View post;
    private View login;
    private TabLayout tabLayout;
    private List<TagDetail> tagDetails = new ArrayList<>();
    private MyAdpater myAdpater;
    private TextView mSearchHint;
    private List<TagDetail> hotSearchTags = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.team_layout, container, false);
        initUi(rootView);
        initData();
        initAction();
        initHotTags();
        return rootView;
    }

    private void initHotTags() {
        List<BcyPair> paramsList = new ArrayList<>();
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + GroupApi.getHotsearch();
        Response.Listener onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject result = new JSONObject(s);
                    String status = result.getString(HttpUtils.UPLOAD_STATUS);
                    if (status.equals("1")) {
                        Gson gson = new Gson();
                        List<Team> data = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<Team>>() {
                        }.getType());
                        processGroupData(data);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSucc, errorProxy);
        VolleyQueue.getRquest(getActivity()).add(stringRequest);
    }

    private void processGroupData(List<Team> data) {
        hotSearchTags.clear();
        if (data != null && !data.isEmpty()) {
            for (int i = 0; i < data.size(); i++) {
                TagDetail tagdetail = new TagDetail();
                tagdetail.setTag_name(data.get(i).getName());
                hotSearchTags.add(tagdetail);
            }
        }
        processHotData();
    }

    private void processHotData() {
        if (hotSearchTags != null && !hotSearchTags.isEmpty()) {
            String hotTag = hotSearchTags.get(0).getTag_name();
            if (!TextUtils.isEmpty(hotTag))
                mSearchHint.setText(String.format(getString(R.string.search_hotgroup_content_format), hotTag));
            else
                mSearchHint.setText(getString(R.string.search_your_interest));
        } else {
            mSearchHint.setText(getString(R.string.search_your_interest));
        }
    }

    @Override
    protected void initUi(View rootview) {
        post = rootview.findViewById(R.id.post_view);
        login = rootview.findViewById(R.id.view_login);
        tabLayout = (TabLayout) rootview.findViewById(R.id.group_tablayout);
        mPager = (ViewPager) rootview.findViewById(R.id.team_pager);
        mSearchHint = (TextView) rootview.findViewById(R.id.textView);

        post.setOnClickListener(this);
        login.setOnClickListener(this);
        rootview.findViewById(R.id.search).setOnClickListener(this);

        if (!TextUtils.isEmpty(UserDataHelper.getInstance(getActivity()).getToken())) {
            post.setVisibility(View.VISIBLE);
            login.setVisibility(View.GONE);
        } else {
            post.setVisibility(View.GONE);
            login.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initAction() {
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        StatService.onEvent(getActivity(), EventConstants.GROUP_HOT, EventConstants.GROUP_HOT);
                        break;
                    case 1:
                        StatService.onEvent(getActivity(), EventConstants.GROUP_ACG, EventConstants.GROUP_ACG);
                        break;
                    case 2:
                        StatService.onEvent(getActivity(), EventConstants.GROUP_EMOTION, EventConstants.GROUP_EMOTION);
                        break;
                    case 3:
                        StatService.onEvent(getActivity(), EventConstants.GROUP_BANGUMI, EventConstants.GROUP_BANGUMI);
                        break;
                    case 4:
                        StatService.onEvent(getActivity(), EventConstants.GROUP_GAMES, EventConstants.GROUP_GAMES);
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void setGroupViewPagerData() {
        getFragment();
        mPager.setOffscreenPageLimit(mList.size());
        myAdpater = new MyAdpater(getChildFragmentManager());
        mPager.setAdapter(myAdpater);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setupWithViewPager(mPager);
        StatService.onEvent(getActivity(), EventConstants.GROUP_HOT, EventConstants.GROUP_HOT);
    }

    private class MyAdpater extends FragmentPagerAdapter {

        public MyAdpater(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mList.get(position);
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tagDetails.get(position).getShow_name();
        }
    }

    private void getFragment() {
        mList.add(new GroupHotFragment());
        for (int i = 0; i < tagDetails.size(); i++) {
            TagDetail tagDetail = tagDetails.get(i);
            GroupTalkFragment groupTalkFragment = new GroupTalkFragment();
            Bundle bundle = new Bundle();
            bundle.putString("id", tagDetail.getWid());
            bundle.putString("type", tagDetail.getType());
            bundle.putString("name", tagDetail.getTag_name());
            groupTalkFragment.setArguments(bundle);
            mList.add(groupTalkFragment);
        }
        TagDetail hotDetail = new TagDetail();
        hotDetail.setShow_name(getResources().getString(R.string.hot));
        tagDetails.add(0, hotDetail);
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + GroupApi.getIndexCircles();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        Map<String, String> map = HttpUtils.getData(paramsList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                    try {
                        JSONObject result = new JSONObject(s);
                        Gson gson = new Gson();
                        tagDetails = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<TagDetail>>() {
                        }.getType());
                        setGroupViewPagerData();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        VolleyQueue.getRquest(getActivity()).add(requestParam);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.post_view:
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        ScreenShots screenShots = new ScreenShots(getActivity());
                        screenShots.takeShot();
                    }
                });
                gotoUtil.gotoAct(getActivity(), StartPostActivity.class, "main");
                getActivity().overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                break;
            case R.id.view_login:
                gotoUtil.gotoAct(getActivity(), LoginActivity.class);
                break;
            case R.id.search:
                gotoSearchActivity();
                break;
            default:
                break;
        }
    }

    private void gotoSearchActivity() {
        Intent intent = new Intent(getActivity(), SearchActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, "group");
        intent.putExtra(gotoUtil.INTENT_VALUE_TWO, (Serializable) hotSearchTags);
        startActivity(intent);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void selfUpdateData() {
        try {
            Fragment currentFragment = myAdpater.getItem(mPager.getCurrentItem());
            ((BaseContainerFragment) currentFragment).selfUpdateData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}